package com.piece.module.flowable.service;

import com.piece.core.framework.util.object.ObjectUtil;
import com.piece.core.jpa.repository.BaseService;
import com.piece.core.log.config.UserContextHolder;
import com.piece.module.flowable.dto.WfTask;
import com.piece.module.flowable.model.WfCopy;
import com.piece.module.flowable.repository.WfCopyRepository;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class WfCopyService extends BaseService<WfCopy, Long> {

    @Autowired
    private WfCopyRepository wfCopyRepository;

    @Resource
    private HistoryService historyService;

    @PostConstruct
    public void initRepository() {
        setRepository(wfCopyRepository);
    }

    /**
     * 增加抄送任务
     */
    public Boolean makeCopy(WfTask wfTask) {
        if (ObjectUtil.isEmpty(wfTask.getCopyUsers())) {
            // 若抄送用户为空，则不需要处理，返回成功
            return true;
        }

        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(wfTask.getProcInsId()).singleResult();
        List<WfCopy> copyList = new ArrayList<>(wfTask.getCopyUsers().size());
        String title = historicProcessInstance.getProcessDefinitionName() + "-" + wfTask.getTaskName();
        String originatorId = UserContextHolder.getUserId();
        String originatorName = UserContextHolder.getUserName();
        try {
            wfTask.getCopyUsers().stream().forEach(copyUserId -> {
                WfCopy copy = new WfCopy();
                copy.setTitle(title);
                copy.setProcessId(historicProcessInstance.getProcessDefinitionId());
                copy.setProcessName(historicProcessInstance.getProcessDefinitionName());
                copy.setDeploymentId(historicProcessInstance.getDeploymentId());
                copy.setInstanceId(wfTask.getProcInsId());
                copy.setTaskId(wfTask.getTaskId());
                copy.setUserId(copyUserId);
                copy.setOriginatorId(originatorId);
                copy.setOriginatorName(originatorName);
                copyList.add(copy);
            });

            wfCopyRepository.batchInsert(copyList);
            return true;
        } catch (Exception e) {
            log.error("增加抄送任务异常:{}", e.getMessage());
            return false;
        }
    }
}
